package com.feeyo.prophet.config.interceptor;

import com.feeyo.prophet.exception.ApiException;
import com.feeyo.prophet.pojo.enums.ResultEnum;
import com.feeyo.prophet.pojo.po.UserInfo;
import com.feeyo.prophet.service.AuthService;
import com.feeyo.prophet.service.InterfaceStatisticsService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {

    private final AuthService authService;

    private final InterfaceStatisticsService interfaceStatisticsService;

    @Autowired
    public AuthInterceptor(AuthService authService, InterfaceStatisticsService interfaceStatisticsService) {
        this.authService = authService;
        this.interfaceStatisticsService = interfaceStatisticsService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String handled = (String) request.getAttribute("handled");
        if (StringUtils.isNotEmpty(handled)) {
            return true;
        }
        String token = request.getHeader("token");
        String appId = request.getHeader("appId");
        String timestamp = request.getHeader("timestamp");
        if (token == null || appId == null || timestamp == null) {
            throw new ApiException(ResultEnum.USER_ILLEGAL_AUTHENTICATION);
        }
        UserInfo userInfo = authService.getUserInfoBy(appId);
        if (null == userInfo) {
            throw new ApiException(ResultEnum.USER_ILLEGAL_AUTHENTICATION);
        }
        String targetToken = authService.generateToken(userInfo.getAppSecret(), timestamp);
        if (!StringUtils.equals(targetToken, token)) {
            throw new ApiException(ResultEnum.USER_ILLEGAL_AUTHENTICATION);
        }
        String uri = request.getRequestURI();
        if (!authService.uriMatch(userInfo.getUris(), uri)) {
            throw new ApiException(ResultEnum.USER_NO_PATH_PERMISSION);
        }
        String key = interfaceStatisticsService.before(appId, uri, request.getRemoteAddr());
        request.setAttribute("stat", key);
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String stat = (String) request.getAttribute("stat");
        if (stat != null) {
            interfaceStatisticsService.after(stat);
        }
    }
}